package com.springsecurity.security.filter;

import com.springsecurity.constants.MessageConstant;
import com.springsecurity.constants.RedisConstant;
import com.springsecurity.constants.TokenConstant;
import com.springsecurity.domain.User;
import com.springsecurity.utlis.AdministratorThreadLocal;
import com.springsecurity.utlis.JwtUtils;
import com.springsecurity.utlis.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * <h3>Spring-Security</h3>
 * <p>过滤器</p>
 *
 * @author gdw
 * @since 2024-07-12 09:13:30
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader(TokenConstant.AUTH_HEADER);
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userName = "";
        try {
            boolean tokenNotExpired = JwtUtils.isTokenNotExpired(token);
            if (!tokenNotExpired) {
                throw new RuntimeException(TokenConstant.OVERDUE);
            }
            Claims claims = JwtUtils.parseJWT(token);
            userName = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(TokenConstant.ERROR);
        }
        //从redis中获取用户信息
        String redisKey = RedisConstant.USER_LOGIN + userName;
        User loginSysUser = (User) redisUtils.get(redisKey);
        if (Objects.isNull(loginSysUser)) {
            throw new RuntimeException(MessageConstant.USER_NOT_LOGIN);
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginSysUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //存入ThreadLocal当中
        AdministratorThreadLocal.setAdministrator(loginSysUser);
        //放行
        filterChain.doFilter(request, response);
    }
}
